"""
add summary column to issues and create issue_summaries history table

Revision ID: 20251119_01
Revises: 20251118_01
Create Date: 2025-11-19 18:40:00
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy import inspect

# revision identifiers, used by Alembic.
revision: str = '20251119_01'
down_revision: Union[str, None] = '20251118_01'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

def upgrade() -> None:
    bind = op.get_bind()
    inspector = inspect(bind)

    # add issues.summary if missing
    issue_cols = {c['name'] for c in inspector.get_columns('issues')}
    if 'summary' not in issue_cols:
        with op.batch_alter_table('issues') as batch_op:
            batch_op.add_column(sa.Column('summary', sa.Text(), nullable=True))

    # create issue_summaries if missing
    existing_tables = set(inspector.get_table_names())
    if 'issue_summaries' not in existing_tables:
        op.create_table(
            'issue_summaries',
            sa.Column('id', sa.Integer(), primary_key=True),
            sa.Column('issue_id', sa.Integer(), sa.ForeignKey('issues.id', ondelete='CASCADE'), nullable=False),
            sa.Column('content', sa.Text(), nullable=False),
            sa.Column('created_at', sa.DateTime(), nullable=True),
        )
        op.create_index('ix_issue_summaries_issue_id', 'issue_summaries', ['issue_id'])


def downgrade() -> None:
    # best-effort reversible downgrade
    bind = op.get_bind()
    inspector = inspect(bind)
    if 'issue_summaries' in inspector.get_table_names():
        try:
            op.drop_index('ix_issue_summaries_issue_id', table_name='issue_summaries')
        except Exception:
            pass
        op.drop_table('issue_summaries')
    issue_cols = {c['name'] for c in inspector.get_columns('issues')}
    if 'summary' in issue_cols:
        with op.batch_alter_table('issues') as batch_op:
            batch_op.drop_column('summary')
